#!/usr/bin/python
import time, sys, os, urllib2, re, smtplib
from email.mime.text import MIMEText; from email.mime.application import MIMEApplication; from email.mime.multipart import MIMEMultipart
# Usage: dshieldcheck.py <proxyserver:port>   (proxy/port are optional)
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
if len(sys.argv) < 2:
    proxy = urllib2.ProxyHandler({})
    proxyid = None
else:
    proxyid = sys.argv[1]
    proxy = urllib2.ProxyHandler({'http': proxyid, 'https': proxyid})
tolist = ["soc@yourdomain.com"]
msg = MIMEMultipart()
msg['From'] = "alerts@yourdomain.com"
msg['To'] = ", ".join(tolist)
msg['Subject'] = "** DShield Search Alert **"
hits = ""
def MailOut():
        server = smtplib.SMTP('[mail server]')
        server.sendmail(msg['From'], tolist, msg.as_string())
        server.quit()
useragent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0"
asn = ['1234', '567', '...', '...']
dshield = 'https://www.dshield.org/asdetailsascii.html?as='
Browser = urllib2.build_opener(proxy)
Browser.addheaders = [ ('User-Agent', useragent) ]
formattedout = ""
date = time.strftime("%Y-%m-%d")
for num in asn:
    site = dshield + num
    check = Browser.open(site).readlines()
    for line in check:
    	if re.search("^[^#\n][0-9\.]+\t[0-9]+\t[0-9]+\t[0-9-]+\t[0-9-]+\t%s"% date, line):
    		line = re.sub("\.0([1-9]+)", ".\\1", line)
    		line = re.sub("\.0+", ".0", line)
    		formattedout += line
if len(formattedout) > 1:
    EmailBody = MIMEText("\n\nIP detected on dShield as an attacking IP. Visit DShield.org for more info:\n\n" +
    "source IP\tReports\tTargets\tFirst Seen\tLast Seen\tUpdated\n" + formattedout)
    msg.attach(EmailBody)
    MailOut()
